import { createRouter, createWebHistory } from "vue-router";
import {
  isLoggedIn,
  hasPermission,
  safeJSONParse,
  clearAdminData,
} from "../utils/auth";
import { ElMessage } from "element-plus";

const routes = [
  // 管理端登录页面 - 最高优先级
  {
    path: "/admin/login",
    name: "AdminLogin",
    component: () => import("../views/admin/Login.vue"),
  },
  {
    path: "/",
    name: "Home",
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/about",
    name: "About",
    component: () => import("../views/subpages/ExhibitionIntro.vue"),
  },
  {
    path: "/exhibitors",
    name: "Exhibitors",
    component: () => import("../views/Exhibitors.vue"),
  },
  {
    path: "/visitors",
    name: "Visitors",
    component: () => import("../views/Visitors.vue"),
  },

  {
    path: "/contact",
    name: "Contact",
    component: () => import("../views/Contact.vue"),
  },
  {
    path: "/downloads",
    name: "Downloads",
    component: () => import("../views/Downloads.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/Register.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/profile",
    name: "Profile",
    component: () => import("../views/Profile.vue"),
    meta: { requiresAuth: true },
  },

  {
    path: "/media-center",
    name: "MediaCenter",
    component: () => import("../views/MediaCenter.vue"),
  },

  {
    path: "/activities",
    name: "Activities",
    component: () => import("../views/Activities.vue"),
  },
  // 展会相关子页面
  {
    path: "/exhibition-overview",
    name: "ExhibitionOverview",
    component: () => import("../views/subpages/ExhibitionOverview.vue"),
  },
  {
    path: "/exhibition-scope",
    name: "ExhibitionScope",
    component: () => import("../views/subpages/ExhibitionScope.vue"),
  },
  {
    path: "/exhibition-highlights",
    name: "ExhibitionHighlights",
    component: () => import("../views/subpages/ExhibitionHighlights.vue"),
  },
  {
    path: "/company-intro",
    name: "CompanyIntro",
    component: () => import("../views/subpages/CompanyIntro.vue"),
  },
  {
    path: "/partners",
    name: "Partners",
    component: () => import("../views/subpages/Partners.vue"),
  },
  {
    path: "/exhibitor-application",
    name: "ExhibitorApplication",
    component: () => import("../views/subpages/ExhibitorApplication.vue"),
  },
  {
    path: "/booth-booking",
    name: "BoothBooking",
    component: () => import("../views/subpages/BoothBooking.vue"),
  },
  {
    path: "/exhibitor-services",
    name: "ExhibitorServices",
    component: () => import("../views/subpages/ExhibitorServices.vue"),
  },
  {
    path: "/exhibitor-info",
    name: "ExhibitorInfo",
    component: () => import("../views/subpages/ExhibitorInfo.vue"),
  },
  {
    path: "/exhibitor-directory",
    name: "ExhibitorDirectory",
    component: () => import("../views/subpages/ExhibitorDirectory.vue"),
  },
  // {
  //   path: '/transportation-guide',
  //   name: 'TransportationGuide',
  //   component: () => import('../views/subpages/TransportationGuide.vue')
  // },
  {
    path: "/activity-schedule",
    name: "ActivitySchedule",
    component: () => import("../views/subpages/ActivitySchedule.vue"),
  },
  {
    path: "/forum-conference",
    name: "ForumConference",
    component: () => import("../views/subpages/ForumConference.vue"),
  },
  {
    path: "/award-ceremony",
    name: "AwardCeremony",
    component: () => import("../views/subpages/AwardCeremony.vue"),
  },

  {
    path: "/news-info",
    name: "NewsInfo",
    component: () => import("../views/subpages/NewsInfo.vue"),
  },
  {
    path: "/photos-videos",
    name: "PhotosVideos",
    component: () => import("../views/subpages/PhotosVideos.vue"),
  },
  {
    path: "/press-release",
    name: "PressRelease",
    component: () => import("../views/subpages/PressRelease.vue"),
  },
  {
    path: "/media-interview",
    name: "MediaInterview",
    component: () => import("../views/subpages/MediaInterview.vue"),
  },
  {
    path: "/media-coverage",
    name: "MediaCoverage",
    component: () => import("../views/subpages/MediaCoverage.vue"),
  },
  // 关于我们模块二级菜单
  {
    path: "/exhibition-intro",
    name: "ExhibitionIntro",
    component: () => import("../views/subpages/ExhibitionIntro.vue"),
  },
  {
    path: "/product-scope",
    name: "ProductScope",
    component: () => import("../views/subpages/ProductScope.vue"),
  },
  {
    path: "/venue-intro",
    name: "VenueIntro",
    component: () => import("../views/subpages/VenueIntro.vue"),
  },
  {
    path: "/organizer-intro",
    name: "OrganizerIntro",
    component: () => import("../views/subpages/OrganizerIntro.vue"),
  },
  {
    path: "/organization-structure",
    name: "OrganizationStructure",
    component: () => import("../views/subpages/OrganizationStructure.vue"),
  },
  {
    path: "/past-exhibitions",
    name: "PastExhibitions",
    component: () => import("../views/subpages/PastExhibitions.vue"),
  },
  // 展商中心模块二级菜单
  {
    path: "/why-exhibit",
    name: "WhyExhibit",
    component: () => import("../views/subpages/WhyExhibit.vue"),
  },
  {
    path: "/who-exhibits",
    name: "WhoExhibits",
    component: () => import("../views/subpages/WhoExhibits.vue"),
  },
  {
    path: "/exhibit-registration",
    name: "ExhibitRegistration",
    component: () => import("../views/subpages/ExhibitRegistration.vue"),
  },
  {
    path: "/exhibitor-system",
    name: "ExhibitorSystem",
    component: () => import("../views/subpages/ExhibitorSystem.vue"),
  },
  {
    path: "/exhibitor-services",
    name: "ExhibitorServices",
    component: () => import("../views/subpages/ExhibitorServices.vue"),
  },
  {
    path: "/exhibitor-notice",
    name: "ExhibitorNotice",
    component: () => import("../views/subpages/ExhibitorNotice.vue"),
  },
  {
    path: "/exhibitor-reviews",
    name: "ExhibitorReviews",
    component: () => import("../views/subpages/ExhibitorReviews.vue"),
  },
  {
    path: "/related-activities",
    name: "RelatedActivities",
    component: () => import("../views/subpages/RelatedActivities.vue"),
  },
  // 观众中心模块二级菜单
  {
    path: "/group-visit",
    name: "GroupVisit",
    component: () => import("../views/subpages/GroupVisit.vue"),
  },
  {
    path: "/visitor-preregistration",
    name: "VisitorPreregistration",
    component: () => import("../views/subpages/VisitorPreregistration.vue"),
  },
  {
    path: "/visitor-notice",
    name: "VisitorNotice",
    component: () => import("../views/subpages/VisitorNotice.vue"),
  },
  // {
  //   path: '/visit-guide',
  //   name: 'VisitGuide',
  //   component: () => import('../views/subpages/VisitGuide.vue')
  // },
  {
    path: "/venue-layout",
    name: "VenueLayout",
    component: () => import("../views/subpages/VenueLayout.vue"),
  },
  {
    path: "/visa-system",
    name: "VisaSystem",
    component: () => import("../views/subpages/VisaSystem.vue"),
  },
  {
    path: "/exhibitors-directory",
    name: "ExhibitorsDirectory",
    component: () => import("../views/subpages/ExhibitorsDirectory.vue"),
  },
  {
    path: "/visitor-roster",
    name: "VisitorRoster",
    component: () => import("../views/subpages/visitorRoster.vue"),
  },
  {
    path: "/visitor-reviews",
    name: "VisitorReviews",
    component: () => import("../views/subpages/VisitorReviews.vue"),
  },
  // 活动中心模块二级菜单
  {
    path: "/activity-overview",
    name: "ActivityOverview",
    component: () => import("../views/subpages/ActivityOverview.vue"),
  },
  {
    path: "/tech-exchange",
    name: "TechExchange",
    component: () => import("../views/subpages/TechExchange.vue"),
  },
  {
    path: "/business-matching",
    name: "BusinessMatching",
    component: () => import("../views/subpages/BusinessMatching.vue"),
  },
  {
    path: "/product-release",
    name: "ProductRelease",
    component: () => import("../views/subpages/ProductRelease.vue"),
  },
  {
    path: "/industry-forum",
    name: "IndustryForum",
    component: () => import("../views/subpages/IndustryForum.vue"),
  },
  {
    path: "/activity-calendar",
    name: "ActivityCalendar",
    component: () => import("../views/subpages/ActivityCalendar.vue"),
  },
  {
    path: "/activity-details",
    name: "ActivityDetails",
    component: () => import("../views/subpages/ActivityDetails.vue"),
  },
  // 媒体中心模块二级菜单
  {
    path: "/exhibition-news",
    name: "ExhibitionNews",
    component: () => import("../views/subpages/ExhibitionNews.vue"),
  },
  {
    path: "/news-detail",
    name: "NewsDetail",
    component: () => import("../views/subpages/NewsDetail.vue"),
  },
  {
    path: "/news-details",
    name: "NewsDetails",
    component: () => import("../views/subpages/NewsDetailTwo.vue"),
  },
  {
    path: "/privacy-policy",
    name: "PrivacyPolicy",
    component: () => import("../views/subpages/PrivacyPolicy.vue"),
  },
  {
    path: "/sys-privacy",
    name: "SystemPrivacy",
    component: () => import("../views/Privacy.vue"),
  },
  {
    path: "/terms-of-service",
    name: "TermsOfService",
    component: () => import("../views/subpages/TermsOfService.vue"),
  },
  {
    path: "/media-reports",
    name: "MediaReports",
    component: () => import("../views/subpages/MediaReports.vue"),
  },
  {
    path: "/industry-news",
    name: "IndustryNews",
    component: () => import("../views/subpages/IndustryNews.vue"),
  },
  {
    path: "/on-site-highlights",
    name: "OnSiteHighlights",
    component: () => import("../views/subpages/OnSiteHighlights.vue"),
  },
  {
    path: "/cooperative-media",
    name: "CooperativeMedia",
    component: () => import("../views/subpages/CooperativeMedia.vue"),
  },
  {
    path: "/partner-media",
    name: "PartnerMedia",
    component: () => import("../views/subpages/PartnerMedia.vue"),
  },
  {
    path: "/media-registration",
    name: "MediaRegistration",
    component: () => import("../views/subpages/MediaRegistration.vue"),
  },
  // 新增功能页面
  // {
  //   path: '/hotel-booking',
  //   name: 'HotelBooking',
  //   component: () => import('../views/subpages/HotelBooking.vue')
  // },
  {
    path: "/exhibitor-detail/:id",
    name: "ExhibitorDetail",
    component: () => import("../views/ExhibitorDetail.vue"),
  },
  {
    path: "/exhibition-detail",
    name: "ExhibitionDetail",
    component: () => import("../views/subpages/ExhibitionDetail.vue"),
  },
  // 活动相关页面
  {
    path: "/activity-registration",
    name: "ActivityRegistration",
    component: () => import("../views/subpages/ActivityRegistration.vue"),
  },
  {
    path: "/product-launch-registration",
    name: "ProductLaunchRegistration",
    component: () => import("../views/subpages/ProductLaunchRegistration.vue"),
  },
  {
    path: "/forum-registration",
    name: "ForumRegistration",
    component: () => import("../views/subpages/ForumRegistration.vue"),
  },
  // 管理端布局路由
  {
    path: "/admin",
    name: "AdminLayout",
    component: () => import("../views/admin/Layout.vue"),
    meta: { requiresAdminAuth: true },
    children: [
      {
        path: "",
        name: "AdminRoot",
        redirect: "/admin/dashboard",
      },
      {
        path: "dashboard",
        name: "AdminDashboard",
        component: () => import("../views/admin/Dashboard.vue"),
        meta: { permission: "dashboard" },
      },
      {
        path: "homepage",
        name: "AdminHomepage",
        component: () => import("../views/admin/Homepage.vue"),
        meta: { permission: "homepage_manage" },
      },
      {
        path: "about",
        name: "AdminAbout",
        component: () => import("../views/admin/About.vue"),
        meta: { permission: "about_manage" },
      },
      {
        path: "approvals",
        name: "AdminApprovals",
        component: () => import("../views/admin/Approvals.vue"),
        meta: { permission: "approval_manage" },
      },
      {
        path: "exhibitors",
        name: "AdminExhibitors",
        component: () => import("../views/admin/Exhibitors.vue"),
        meta: { permission: "exhibitor_manage" },
      },
      {
        path: "products",
        name: "AdminProducts",
        component: () => import("../views/admin/Products.vue"),
        meta: { permission: "product_manage" },
      },
      {
        path: "exhibitor-content",
        name: "AdminExhibitorContent",
        component: () => import("../views/admin/ExhibitorContent.vue"),
        meta: { permission: "exhibitor_content_manage" },
      },
      {
        path: "visitors",
        name: "AdminVisitors",
        component: () => import("../views/admin/Visitors.vue"),
        meta: { permission: "visitor_manage" },
      },
      {
        path: "group-visit",
        name: "AdminGroupVisit",
        component: () => import("../views/admin/GroupVisit.vue"),
        meta: { permission: "visitor_manage" },
      },
      {
        path: "visitor-content",
        name: "AdminVisitorContent",
        component: () => import("../views/admin/VisitorContent.vue"),
        meta: { permission: "visitor_content_manage" },
      },
      {
        path: "visa",
        name: "AdminVisa",
        component: () => import("../views/admin/Visa.vue"),
        meta: { permission: "visa_manage" },
      },
      {
        path: "tickets",
        name: "AdminTickets",
        component: () => import("../views/admin/Tickets.vue"),
        meta: { permission: "ticket_manage" },
      },
      {
        path: "activities",
        name: "AdminActivities",
        component: () => import("../views/admin/Activities.vue"),
        meta: { permission: "activity_manage" },
      },
      {
        path: "activity-content",
        name: "AdminActivityContent",
        component: () => import("../views/admin/ActivityContent.vue"),
        meta: { permission: "activity_content_manage" },
      },
      {
        path: "media-info",
        name: "AdminMediaInfo",
        component: () => import("../views/admin/MediaInfo.vue"),
        meta: { permission: "media_manage" },
      },
      {
        path: "media-regitser",
        name: "AdminRegisterMedia",
        component: () => import("../views/admin/RegisterMedia.vue"),
        meta: { permission: "media_manage" },
      },
      {
        path: "media",
        name: "AdminMedia",
        component: () => import("../views/admin/Media.vue"),
        meta: { permission: "media_manage" },
      },
      {
        path: "downloads",
        name: "AdminDownloads",
        component: () => import("../views/admin/Downloads.vue"),
        meta: { permission: "download_manage" },
      },
      {
        path: "users",
        name: "AdminUsers",
        component: () => import("../views/admin/Users.vue"),
        meta: { permission: "user_manage" },
      },
      {
        path: "permissions",
        name: "AdminPermissions",
        component: () => import("../views/admin/Permissions.vue"),
        meta: { permission: "permission_manage" },
      },
      {
        path: "menus",
        name: "AdminMenus",
        component: () => import("../views/admin/Menus.vue"),
        meta: { permission: "menu_manage" },
      },
      {
        path: "settings",
        name: "AdminSettings",
        component: () => import("../views/admin/Settings.vue"),
        meta: { permission: "system_setting" },
      },
      {
        path: "contacts",
        name: "AdminContacts",
        component: () => import("../views/admin/Contacts.vue"),
        meta: { permission: "system_setting" },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 管理端登录页面完全独立，不进行任何检查
  if (to.path === "/admin/login") {
    next();
    return;
  }

  // 如果是管理端相关路由，优先处理管理端逻辑
  if (to.path.startsWith("/admin")) {
    // 检查管理端登录
    if (to.meta.requiresAdminAuth) {
      const adminToken = localStorage.getItem("adminToken");
      const adminUser = localStorage.getItem("adminUser");

      if (!adminToken || !adminUser || adminUser === "undefined") {
        ElMessage.warning("请先登录管理后台");
        next("/admin/login");
        return;
      }

      const userData = safeJSONParse(adminUser, {});

      if (!userData || (!userData.userCode && !userData.userId)) {
        console.error("用户数据为空或解析失败");
        clearAdminData();
        ElMessage.error("登录信息异常，请重新登录");
        next("/admin/login");
        return;
      }

      // 检查token是否过期（简单检查，实际项目中可能需要更复杂的验证）
      try {
        const tokenPayload = JSON.parse(atob(adminToken.split(".")[1]));
        const currentTime = Math.floor(Date.now() / 1000);
        if (tokenPayload.exp && tokenPayload.exp < currentTime) {
          clearAdminData();
          ElMessage.error("登录已过期，请重新登录");
          next("/admin/login");
          return;
        }
      } catch (error) {
        // token格式错误，清除数据并跳转登录
        clearAdminData();
        ElMessage.error("登录信息异常，请重新登录");
        next("/admin/login");
        return;
      }

      // 检查特定权限
      if (to.meta.permission) {
        const hasPermission =
          userData.permissions?.includes("all") ||
          userData.permissions?.includes(to.meta.permission) ||
          userData.roles?.some(
            (role) =>
              role.roleCode === "super_admin" || role.roleCode === "admin"
          );

        if (!hasPermission) {
          ElMessage.error("没有访问权限");
          next("/admin/dashboard");
          return;
        }
      }
    }

    // 管理端路由处理完毕，继续
    next();
    return;
  }

  // 检查用户端登录
  if (to.meta.requiresAuth && !isLoggedIn()) {
    ElMessage.warning("请先登录");
    next("/login");
    return;
  }

  // 检查管理员权限
  if (to.meta.requiresAdmin && !hasPermission("admin")) {
    ElMessage.error("没有管理员权限");
    next("/");
    return;
  }

  // 检查特定权限
  if (to.meta.permission && !hasPermission(to.meta.permission)) {
    ElMessage.error("没有访问权限");
    next("/");
    return;
  }

  next();
});

export default router;
